<template>
  <div>
    <div class="event-select task-flex task-ai">
      <!-- 产品类型 -->
      <div class="task-flex task-ai task-mr24">
        <span>{{$t('common.base.productType')}}：</span>
        <Treeselect 
          class="task-span1"
          v-model="productId" 
          :multiple="true"
          :clearAllText="''"
          :normalizer="normalizer"
          :placeholder="$t('product.setting.qrCodeSet.associateDialog.pla1')"
          value-consists-of="ALL"
          :noResultsText="$t('common.base.tip.noData')"
          :options="catalogOption"
          :limit="1"
          :limitText="count => `+ ${count}`"
          @select="delayParams"
          @deselect="delayParams" />
      </div>
      <!-- 时间 -->
      <div class="task-flex task-ai">
        <span>{{$t('common.base.createTime')}}：</span>
        <el-date-picker
          class="task-span1"
          v-model="dataTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          align="right"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          @change="paramsAndTrack('REPORT_SEARCH_TIME')"
        >
        </el-date-picker>
      </div>
    </div>

    <div class="event-select task-flex task-ai task-mt12">
      <!-- 工单 和 事件 -->
      <div class="task-flex task-ai task-mr24">
        <span>{{reportType === 'product_task' ? `${$t('common.fields.taskType.displayName')}` : $t('common.label.eventType')}}</span>
        <el-select
          v-model="taskId"
          multiple
          clearable
          :placeholder="reportType === 'product_task' ? $t('report.taskSelect.placeholder1') : $t('event.setting.serviceEventTypeSetting.manage.component.addServiceEventDialog.tips2')"
          class="task-span1"
          @change="paramsAndTrack(reportType === 'product_task' ? 'REPORT_SEARCH_TASKTYPE' : '')"
          @clear="Params">
          <el-option
            v-for="item in taskList"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div class="task-flex task-ai">
        <span>{{$t('common.task.flow.finishTime')}}：</span>
        <el-date-picker
          class="task-span1"
          v-model="completeTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          :range-separator="$t('common.base.to')"
          :start-placeholder="$t('common.base.startDate')"
          :end-placeholder="$t('common.base.endDate')"
          align="right"
          value-format="timestamp"
          :default-time="['00:00:00', '23:59:59']"
          @change="paramsAndTrack('REPORT_SEARCH_TIME')"
        >
        </el-date-picker>
      </div>
    </div>
  </div>
</template>
<script>
// API
import * as ReportApi from '@src/api/ReportApi.ts';
import { cloneData } from '@src/api/ProductV2Api';

import { nearDateBy, dayTimeEnd, useDatePicker } from 'pub-bbx-utils';
import { t } from '@src/locales'
const datePicker = useDatePicker()

import Treeselect from '@riophae/vue-treeselect';
import '@riophae/vue-treeselect/dist/vue-treeselect.css';

export default {
  name: 'product-select',
  props: {
    reportType: {
      type: String // 报表类型
    }
  },
  components: {
    Treeselect,
  },
  data() {
    const startTime = +nearDateBy(1, 'week');
    const endTime = +dayTimeEnd();

    return {
      catalogOption: [],
      pickerOptions: {
        shortcuts: [
          datePicker.today(t('common.time.today')),
          datePicker.yesterday(t('common.time.yesterday')),
          datePicker.nearDate(t('common.time.lastWeek'), 1, 'week'),
          datePicker.nearDate(t('common.time.lastMonth'), 1, 'month'),
          datePicker.nearDate(t('common.time.lastThreeMonth'), 3, 'month'),  
        ]
      },
      productId: [], // 产品
      dataTime: [startTime, endTime], // 时间
      taskId: '', // 工单类型
      taskList: [], // 工单类型列表
      productList: [], // 产品列表
      completeTime: [startTime, endTime] // 完成时间
    }
  },
  mounted() {
    this.taskTypes()
    this.productType()
    this.Params()
    this.getCatalogOption()
  },
  methods: {
    // 工单类型
    async taskTypes() {
      this.taskList = []
      const {succ, data} = await ReportApi.taskType()
      if (succ) {
        for(let key in data) {
          this.taskList.push({
            value: key,
            label: data[key]
          })
        }
      }
    },
    // 产品类型
    async productType() {
      const res = await ReportApi.productType()
      this.productList = res.map(item => {
        return {
          value: item
        }
      })
    },
    paramsAndTrack(trackId) {
      this.Params()
      this.reportType && trackId && this.$track.commonFn.chartTrack(this.reportType, trackId, this.$track)
    },
    // 参数
    Params() {
      const {dataTime, taskId, productId, completeTime} = this
      this.$emit('taskParams', {
        productTypes: productId,
        taskTypeIds: taskId,
        timeStart: dataTime?.[0],
        timeEnd: dataTime?.[1],
        completeTimeStart: completeTime?.[0],
        completeTimeEnd: completeTime?.[1],
      })
    },
    // 获取树结构
    async getCatalogOption () {
      try{
        let {code,result,message} = await cloneData();
        if(code === 0) {
          this.deleteEmpty(result);
          this.catalogOption = result;
        }else{
          this.$platform.notification({
            type: 'error',
            title: this.$t('common.base.tip.httpIsError'),
            message: message
          })
        }
      }catch(err){
        console.error(err);
      }
    },
    // 删除空子集
    deleteEmpty (list) {
      list.forEach(item => {
        if(!item.tasks.length){
          delete item.tasks;
        }else{
          this.deleteEmpty(item.tasks);
        }
      });
    },
    normalizer(node) {
      return {
        id: node.name,
        label: node.name,
        children: node.tasks,
      }
    },
    delayParams(){
      const t = setTimeout(() => {
        this.Params();
        clearTimeout(t);
      });
    },
  }
}
</script>

<style lang="scss" scoped>
@import '../system.scss';
</style>
<style lang="scss">
.event-select {
    .el-range-separator {
        width: 10%!important;
    }
}
</style>